package com.douyuehan.doubao.wechatpay.utils;


public class WechatAccessTokenHolder {

    private static WechatAccessTokenHolder instance;
    private AccessToken accessToken;


    private WechatAccessTokenHolder() {

    }

    public synchronized static WechatAccessTokenHolder getInstance() {
        if (instance == null) instance = new WechatAccessTokenHolder();
        return instance;
    }

    public synchronized AccessToken getAccessToken() {
        if (accessToken == null || accessToken.expired()) {
            refreshToken();
        }
        return accessToken;
    }

    public synchronized void refreshToken() {
        if (accessToken == null || accessToken.expired()) {
            String content = fetchAccessToken();
            AccessToken accessToken = AccessToken.fromJson(content);
            this.accessToken = accessToken;
        }
    }

    public void expireToken() {
        accessToken.setExpiresIn(-30);//强制设置为无效
    }

    protected String fetchAccessToken() {
        return WeChatClient.get(WeChatApi.tokenUrl());
    }

}
